package com.springboot.filter;

import com.alibaba.fastjson.JSON;
import com.springboot.common.BaseContext;
import com.springboot.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter ( filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg", //移动端发送短信
                "/user/login" //移动端登录
        };
        boolean b = checkLogin(urls, uri); //判断是否需要登录,是否需要处理
        if (b) {
            log.info("本次不需要处理的请求路径：{}", uri);
            filterChain.doFilter(request, response);
            return;
        }
        //判断是否登录,如果登录，则放行，否则返回未登录
        if (request.getSession().getAttribute("employee") != null) {
            log.info("登录成功，放行请求路径：{}", uri);
           Long empid=(Long)request.getSession().getAttribute("employee");
            BaseContext.setUserId(empid);
            long id = Thread.currentThread().getId();
            log.info("线程id：{}", id);
            filterChain.doFilter(request, response);
            return;
        }
        //判断移动端是否登录,如果登录，则放行，否则返回未登录
        if (request.getSession().getAttribute("user") != null) {
            log.info("登录成功，放行请求路径：{}", uri);
            Long userid=(Long)request.getSession().getAttribute("user");
            BaseContext.setUserId(userid);
            long id = Thread.currentThread().getId();
            log.info("线程id：{}", id);
            filterChain.doFilter(request, response);
            return;
        }
        log.info("拦截的请求路径：{}" ,uri);
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }
    public  boolean checkLogin(String[] urls,String uri) {
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, uri);
            if (match) {
                return true;
            }
        }
        return false;

    }
    }

